/**
 * @file Implements CommandQueue.
 * @author Zmei Zelen <zmei.zelen@gmail.com>
 */

function CommandQueue(id) {
    this.id = id;
    this.on = new EventSet();
    this.on.add('out');
    this.queue = [];
}


CommandQueue.prototype.add = function (command) {       
    if (typeof command.time === 'undefined') command.time = new Date().getTime();
    this.queue.push(command);
};


CommandQueue.prototype.pop = function () {
    return this.queue.shift();
};


CommandQueue.prototype.next = function () {
    var command = this.pop();    
    if (command) this.on.fire('out', command);
    return command;
};


CommandQueue.prototype.source = function (source, map) {      
    source.on.out((function(command) {
        var a = command;
        command = Utils.copy(command);
        if (map !== undefined) command.which = map[command.which];        
        if (command.which !== undefined) this.add(command);        
    }).bind(this));
};